package com.sen.mqtt.config;

import com.sen.mqtt.domain.MqttConfigurationProperties;
import com.sen.mqtt.hanler.ReceiverMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * 订阅主题获取消息 配置
 *
 * @作者 韩宗森
 * @创建时间 2025年01月22日 16:35
 */
@Configuration
public class MqttInboundConfiguration {

    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;

    @Autowired
    private ReceiverMessageHandler receiverMessageHandler;

    /**
     * 配置消息传输通道
     *
     * @return
     */
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }


    /**
     * 配置入站适配器
     * 作用，设置订阅主题，以及指定消息的相关属性
     */
    @Bean
    public MessageProducer messageProducer(MqttPahoClientFactory mqttPahoClientFactory) {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(
                        mqttConfigurationProperties.getUrl(),
                        mqttConfigurationProperties.getSubClientId(),
                        mqttPahoClientFactory,
                        mqttConfigurationProperties.getSubTopic().split(","));
        // 默认消息转换器
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        // 消息通道
        adapter.setOutputChannel(mqttInputChannel());

        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")// 指定获取消息的通道  上面定义的通道
    public MessageHandler mqttMessageHandler() {
        return receiverMessageHandler;
    }

}
